﻿using CCSSolderUI.Common.Event;
using CCSSolderUI.Models;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace CCSSolderUI.ViewModels.Dialogs
{
    public class PartNumberDialogViewModel : BindableBase, IDialogAware
    {
        #region 变量
        SystemParam systemParam;
        private readonly IDialogService _dialogService;
        private readonly IEventAggregator _eventAggregator;
        #endregion
        #region 属性
        private string currentPartNumber;
        public string CurrentPartNumber
        {
            get { return currentPartNumber; }
            set { SetProperty(ref currentPartNumber, value); }
        }
        private ObservableCollection<PartNumberDisp> partNumberList = new ObservableCollection<PartNumberDisp>();
        public ObservableCollection<PartNumberDisp> PartNumberList
        {
            get { return partNumberList; }
            set { SetProperty(ref partNumberList, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand addCommand;
        public DelegateCommand AddCommand =>
            addCommand ?? (addCommand = new DelegateCommand(ExecuteAddCommand));
        private DelegateCommand<object> deleteCommand;
        public DelegateCommand<object> DeleteCommand =>
            deleteCommand ?? (deleteCommand = new DelegateCommand<object>(ExecuteDeleteCommand));

        void ExecuteDeleteCommand(object obj)
        {
            if (obj != null)
            {
                var pn = (PartNumberDisp)obj;
                if (pn.Name != CurrentPartNumber)
                {
                    if (MessageBox.Show($"你确定删除料号{pn.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        systemParam.ProductList.Remove(pn.Name);
                        //删除文件夹
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, pn.Name));
                        // Delete this dir and all subdirs.
                        try
                        {
                            di.Delete(true);
                        }
                        catch (System.IO.IOException ex)
                        {
                            _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message { Sender = "PartNumberDialog", Type = "Print", Content = $"删除文件出错:{ex.Message}" });
                        }
                        PartNumberList.Clear();
                        int i = 0;
                        foreach (var item in systemParam.ProductList)
                        {
                            PartNumberList.Add(new PartNumberDisp { Id = i++, Name = item });
                        }
                        var curp = PartNumberList.FirstOrDefault(p => p.Name == CurrentPartNumber);
                        if (curp != null)
                        {
                            systemParam.Index = curp.Id;
                            string jsonString = JsonConvert.SerializeObject(systemParam, Newtonsoft.Json.Formatting.Indented);
                            File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "SystemParam.json"), jsonString);
                            _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message { Sender = "PartNumberDialog", Type = "Delete", Content = "" });
                        }
                    }
                }
                else
                {
                    MessageBox.Show($"料号{pn.Name}正在使用，不能删除！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("未选择任何料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private DelegateCommand<object> selectCommand;
        public DelegateCommand<object> SelectCommand =>
            selectCommand ?? (selectCommand = new DelegateCommand<object>(ExecuteSelectCommand));

        void ExecuteSelectCommand(object obj)
        {
            if (obj != null)
            {
                var pn = (PartNumberDisp)obj;
                if (CurrentPartNumber != pn.Name)
                {
                    if (MessageBox.Show($"你确定选择料号{pn.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        systemParam.Index = pn.Id;
                        string jsonString = JsonConvert.SerializeObject(systemParam, Newtonsoft.Json.Formatting.Indented);
                        File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "SystemParam.json"), jsonString);
                        CurrentPartNumber = systemParam.ProductList[systemParam.Index];
                        _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message { Sender = "PartNumberDialog", Type = "Select", Content = pn.Name });
                        MessageBox.Show($"更新料号为{systemParam.ProductList[systemParam.Index]}", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何料号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteAddCommand()
        {
            _dialogService.ShowDialog("AddNewPNDialog", arg => {
                if (arg.Result == ButtonResult.Yes)
                {
                    string NewPNName = arg.Parameters.GetValue<string>("NewPNName");
                    if (NewPNName != "")
                    {
                        var fpn = systemParam.ProductList.FirstOrDefault(t => t == NewPNName);
                        if (fpn != null)
                        {
                            MessageBox.Show($"新料号{NewPNName}料号名称重复", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            systemParam.ProductList.Add(NewPNName);
                            PartNumberList.Clear();
                            int i = 0;
                            foreach (var item in systemParam.ProductList)
                            {
                                PartNumberList.Add(new PartNumberDisp { Id = i++, Name = item });
                            }
                            string jsonString = JsonConvert.SerializeObject(systemParam, Newtonsoft.Json.Formatting.Indented);
                            File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "SystemParam.json"), jsonString);

                            try
                            {
                                //创建新文件夹
                                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, NewPNName));
                                //复制数据                                        
                                FileHelper.DirectoryCopy(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, CurrentPartNumber), System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, NewPNName), true);
                                MessageBox.Show($"新料号{NewPNName}创建完成", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            catch (Exception ex)
                            {
                                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message { Sender = "PartNumberDialog", Type = "Print", Content = $"复制文件出错:{ex.Message}" });
                                MessageBox.Show($"复制文件出错:{ex.Message}", "确认", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }

                        }
                    }
                }
            });
        }
        #endregion
        #region 导航
        public string Title => "料号";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            PartNumberList.Clear();
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "SystemParam.json"));
                systemParam = JsonConvert.DeserializeObject<SystemParam>(jsonString);
                int i = 0;
                foreach (var item in systemParam.ProductList)
                {
                    PartNumberList.Add(new PartNumberDisp { Id = i++, Name = item });
                }
                CurrentPartNumber = systemParam.ProductList[systemParam.Index];
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        #endregion
        #region 构造函数
        public PartNumberDialogViewModel(IEventAggregator ea, IDialogService ds)
        {
            _dialogService = ds;
            _eventAggregator = ea;
        }
        #endregion
        #region 功能函数
        
        #endregion
    }
    public class PartNumberDisp
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
